<template>
    <el-form :model="formData" label-position="top" v-loading="loading" ref="formRefs" :rules="rules">
        <el-row :gutter="30">
            <el-col :span="12">
                <el-form-item size="large" :label="$t('course.unit_edit.label_1')" class="w-1/2" prop="title_cn">
                    <el-input v-model="formData.title_cn" :placeholder="$t('course.unit_edit.label_1_placeholder')" />
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item size="large" :label="$t('course.unit_edit.label_2')" class="w-1/2" prop="title_en">
                    <el-input v-model="formData.title_en" :placeholder="$t('course.unit_edit.label_2_placeholder')" />
                </el-form-item>
            </el-col>
        </el-row>
        <el-form-item size="large" :label="$t('course.unit_edit.label_3')" prop="icon_url">
            <el-upload :show-file-list="false" :before-upload="beforeAvatarUpload" accept="image/jpeg, image/png" :http-request="handleUpload">
                <div class="unit-img pic">
                    <img v-if="formData.icon_url" :src="formData.icon_url" class="ele" />
                    <el-icon v-else size="35" color="#dcdfe6"><Plus /></el-icon>
                </div>
                <template #tip>
                    <p>{{ $t('course.unit_edit.label_3_placeholder') }}</p>
                </template>
            </el-upload>
        </el-form-item>
        <el-form-item size="large" :label="$t('course.unit_edit.label_4')" prop="description">
            <RichTextEditor v-model="formData.description" @update-richValue="formData.description = $event" />
        </el-form-item>
        <el-form-item size="large">
            <el-button color="#f06423" @click="handleSave(false)">{{ $t('golbal.btn_text_1') }}</el-button>
            <el-button color="#f06423" @click="handleSave(true)">{{ $t('golbal.btn_text_2') }}</el-button>
            <el-button color="#f06423" @click="router.go(-1)">{{ $t('golbal.btn_text_3') }}</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

import { ElMessage, type FormInstance, type UploadRequestOptions } from 'element-plus'

import RichTextEditor from '@/components/RichTextEditor.vue'

import ResourceService from '@/api/resource'

import UnitService from '@/api/unit'
import type { UnitItem, UnitItemCreate } from '@/types/unit'

import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

const route = useRoute()
const router = useRouter()
const unitId = computed(() => Number(route.params.unitId))
const courseId = computed(() => Number(route.params.courseId))
const loading = ref(false)
const { t } = useI18n<{ message: MessageSchema }, SupportedLocales>()

const formRefs = ref<FormInstance>()
const formData = ref<UnitItem>({
    id: unitId.value,
    course_id: courseId.value,
    title_cn: '',
    title_en: '',
    title: '',
    description: '',
    icon_url: '',
    sort_order: 0,
    is_completed: false,
    resources: [],
    _resources: {},
})
const rules = {
    title_cn: [{ required: true, message: t('course.unit_edit.label_1_placeholder'), trigger: 'blur' }],
    title_en: [{ required: true, message: t('course.unit_edit.label_2_placeholder'), trigger: 'blur' }],
    icon_url: [{ required: true, message: t('course.unit_edit.label_3_placeholder'), trigger: 'change' }],
    // description: [{ required: true, message: t('course.unit_edit.label_4_placeholder'), trigger: 'change' }],
}
function getUnitInfo() {
    loading.value = true
    UnitService.getById(unitId.value)
        .then(res => {
            formData.value = res
        })
        .finally(() => {
            loading.value = false
        })
}
const handleSave = (isBack: boolean = false) => {
    if (!formRefs.value) return

    formRefs.value.validate((valid: boolean, fields: any) => {
        if (valid) {
            loading.value = true
            const data: any = { ...formData.value }
            delete data.resources
            delete data._resources
            data.course_id = courseId.value
            if (unitId.value) {
                data.id = unitId.value
            } else {
                delete data.id
            }
            UnitService.save(data)
                .then(res => {
                    if (isBack) return router.go(-1)
                    if (!unitId.value) {
                        formData.value.id = res.id
                        router.replace({
                            name: 'unitEdit',
                            params: {
                                unitId: res.id,
                                courseId: courseId.value,
                            },
                        })
                    }
                })
                .finally(() => {
                    loading.value = false
                })
        } else {
            loading.value = false
        }
    })
}

// 上传
const beforeAvatarUpload = (file: File) => {
    const isLt500M = file.size / 1024 / 1024 < 500
    if (!isLt500M) {
        ElMessage.error(`${t('golbal.upload_err_1')} 500MB!`)
        return false
    }
    return true
}
const handleUpload = (options: UploadRequestOptions) => {
    const { file } = options
    const data = new FormData()
    data.append('file', file)
    data.append('type', 'image')
    data.append('filename', file.name)
    ResourceService.upload(data).then(res => {
        formData.value.icon_url = res.url
    })
}

onMounted(() => {
    if (unitId.value) getUnitInfo()
})
</script>

<style lang="less" scoped>
.el-form {
    .el-form-item {
        p {
            margin-top: 4px;
            font-size: 12px;
            color: #4c4c4c;
            line-height: 1.2;
        }
    }
}

:deep(.el-upload) {
    .unit-img {
        border: 1px solid #dcdfe6;
        width: 100px;
        height: 100px;

        display: flex;
        align-items: center;
        justify-content: center;
    }
}

:deep(.ck-editor) {
    width: 100%;

    .ck-editor__main {
        .ck-content {
            min-height: 350px;
            max-height: 600px;
        }
    }
}
</style>
